import React, { ReactElement, useEffect, useState } from 'react';
import { Table } from 'antd';
import { InbizIcon } from '@inbiz/utils';
import { getMessage } from '@inbiz/react';
import { choeseData } from './index';
import PageComponent from '../MemberSelect/components/PageComponent';
import './index.less';

type Iprops = {
  listData: {
    createTime: string;
    id: number;
    key: string;
    title: string;
    namePath: string;
    pId: number;
    path: string;
    type: number;
    pos: React.Key[];
  }[];
  selectValueFn: (value: choeseData) => void;
  total: number;
  changeData: (size: number, pageIndex: number) => void;
  searchWord: string;
};
function DocList(props: Iprops): ReactElement {
  const { listData } = props;
  const [size, setSize] = useState(10);
  const [pageIndex, setPageIndex] = useState(1);
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const onSelectChange = (keys: string[]) => {
    // 单选框的单选
    setSelectedRowKeys(keys);
    let nowData: any = listData?.find((item) => item.key == keys[0]);
    props.selectValueFn({
      id: keys[0],
      categoryType: nowData.type,
      title: nowData.title,
      pos: nowData.pos,
    });

    // 多选框单选
    // if (keys.length > 1) {
    //     setSelectedRowKeys([keys[1]]);
    //     props.selectValueFn(keys[1]);
    //   } else {
    //     setSelectedRowKeys(keys);
    //     props.selectValueFn(keys[0]);
    //   }
    // setSelectedRowKeys((data) => { return [...selectedRowKeys] })
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const onRow = function (record: any) {
    return {
      onClick: () => {
        setSelectedRowKeys([record.key]);
        let nowData: any = listData.find((item) => item.key == record.key);
        props.selectValueFn({
          id: record.key,
          categoryType: nowData.type,
          title: nowData.title,
          pos: nowData.pos,
        });
      },
    };
  };

  // 分页相关的逻辑
  // const pagination = {
  //     pageSize: size,
  //     total: props.total,
  //     showSizeChanger: true,
  //     showQuickJumper: true,
  //     onChange: (pageIndex: number, pageSize: number) => {
  //         setPageIndex(pageIndex);
  //         setSize(pageSize);
  //         props.changeData(pageSize, pageIndex);
  //     },
  //     onShowSizeChange: (current: number, size: number) => {
  //         setSize(size);
  //         setPageIndex(current);
  //         props.changeData(size, current);
  //     },
  //     onSelectAll: () => { },
  // };
  useEffect(() => {
    props.changeData(size, pageIndex);
  }, [size, pageIndex]);

  // 表配置（表头和渲染数据的逻辑）
  const columns = [
    {
      title: getMessage('ClassPicker.name'), // 名称
      dataIndex: 'title',
      width: '99%',
      render: (text: string, data: any) => {
        return (
          <div className="tableItem">
            {/* <img className="docImg" src={util.getRowIcon(record)} /> */}
            {data.type == 0 ? (
              <InbizIcon
                type="icon-tupian"
                style={{
                  fontSize: 16,
                  marginRight: 5,
                  color: 'var(--inbiz-color-primary)',
                }}
              />
            ) : (
              <InbizIcon
                type="icon-xinwen"
                style={{
                  fontSize: 16,
                  marginRight: 5,
                  color: 'var(--inbiz-color-primary)',
                }}
              />
            )}
            <span
              title={text}
              className="tableItemText"
              dangerouslySetInnerHTML={{ __html: renderSearText(text) }}
            ></span>
          </div>
        );
      },
    },
  ];
  // 展示搜索结果总数
  const SearchToltal = () => {
    return (
      <span className="searchTotal">{`${getMessage('ClassPicker.allResult')} ${props.total || 0
        } ${getMessage('ClassPicker.single')}`}</span>
    ); // 共搜索相关结果 * 个
  };

  // 正则替换，关键词飘红
  function renderSearText(content: string) {
    let regStr = `(${props.searchWord})`;
    let reg = new RegExp(regStr, 'g');
    return content.replace(
      reg,
      `<span style=color:red>${props.searchWord}</span>`,
    );
  }

  return (
    <div className="docList" style={{}}>
      <Table
        rowSelection={{
          hideSelectAll: true,
          type: 'radio',
          renderCell: () => {
            return '';
          },
          ...rowSelection,
        }}
        columns={columns}
        onRow={onRow}
        // pagination={{ size: 'small', ...pagination }}
        pagination={false}
        dataSource={listData}
        scroll={{ y: 323 }}
        rowClassName={'tableRow'}
      />
      <PageComponent
        total={props.total}
        current={pageIndex}
        pageSize={size}
        setPageSize={setSize}
        setCurrent={setPageIndex}
      ></PageComponent>
      {listData.length ? <SearchToltal /> : ''}
    </div>
  );
}
export default DocList;
